package com.song.springcloud.controller;


import com.song.springcloud.pojo.User;
import com.song.springcloud.servcie.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

//提供Restful服务
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    //获取微服务配置信息，得到具体的微服务
    @Resource
    private DiscoveryClient client;

    @PostMapping("/user/add")
    public boolean addUser(User user) {
        return userService.addUser(user);
    }

    @GetMapping("/user/get/{userId}")
    @ResponseBody
    public User addUser(@PathVariable long userId) {
        User user = userService.queryUserById(userId);
        return user;
    }

    @GetMapping("/user/list")
    public List<User> queryAll() {
        System.out.println("进入了controller!!!");
        return userService.queryAll();
    }

    //注册进来的微服务，获取一些信息   http://localhost:8001/user/discovery
    @GetMapping("/user/discovery")
    public Object discovery() {
        //获取微服务列表清单
        List<String> services = client.getServices();
        System.out.println("discovery=>services:" + services);

        //得到一个具体的微服务信息，通过具体的微服务id,applicationName
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-USER");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost() + "\t" +
                            instance.getPort() + "\t" +
                            instance.getUri() + "\t" +
                            instance.getServiceId()
            );
        }
        return this.client;
        /*
            discovery=>services:[springcloud-provider-user]
            192.168.52.49	8001	http://192.168.52.49:8001	SPRINGCLOUD-PROVIDER-USER
         */
    }
}
